package com.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.pojo.FlightExcel;
import com.pojo.FlightExcelGet;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;

@EqualsAndHashCode(callSuper = true)
@Data
public class FlightExcelLisener extends AnalysisEventListener<FlightExcel> {
    private String fileName;
    private String exportFolders;

    private final List<FlightExcelGet> flightExcelGets = new LinkedList<>();

    /**
     * 这个每一条数据解析都会来调用
     */
    public void invoke(FlightExcel flightExcel, AnalysisContext analysisContext) {
        FlightExcelGet flightExcelGet = new FlightExcelGet();
        flightExcelGet.setOrderId("飞行编号:" + flightExcel.getFlightNumber() + ",起飞时间:" + flightExcel.getDepartureTime() + ",降落时间:" + flightExcel.getFallTime());
        String trackPointSequence = flightExcel.getTrackPointSequence();
        flightExcelGet.setPath(trackPointSequence);
        flightExcelGets.add(flightExcelGet);
    }

    /**
     * 所有数据读取完了调用
     */
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        String jsonString = JSON.toJSONString(flightExcelGets);

        System.out.println("读取完毕 所有数据  ");

        BufferedWriter bw;
        try {
            fileName = fileName.substring(0, fileName.lastIndexOf("."));
            String out = exportFolders+fileName+".js";
            System.out.println(out);
            bw = new BufferedWriter(new FileWriter(out));
            bw.write(jsonString);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean hasAllFieldsWithValue(Object obj) throws IllegalAccessException {
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            Object value = field.get(obj);

            if (value == null) {
                return false;
            }
        }

        return true;
    }

}

